import logging
import socket

logger = logging.getLogger(__name__)

class EthernetBase:
    def __init__(self, local_ip: str = None, local_port: int = None, ip: str = None, port: int = None):
        self.ip = local_ip
        self.port = local_port
        self.addr = (ip, port)
        self.ethernet = None

    def loadConfig(self, config: dict = None):
        try:
            self.ip = config["local_ip"]
            self.port = config["local_port"]
            self.addr = (config["ip"], config["port"])
            return True
        except:
            return False

    def InitConnect(self):
        if self.ip is not None and self.port is not None:
            try:
                self.ethernet = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                self.ethernet.bind((self.ip, self.port))
                logger.info(f"Success to connect ip:{self.ip} and port:{self.port}")
                return True
            except:
                logger.error(f"Failed to connect ip:{self.ip} and port:{self.port}")
                return False
        else:
            logger.error("Failed to connect Ethernet!")
            return False

    def close(self):
        if self.ethernet is not None:
            self.ethernet.close()
            return True
        else:
            return False

    def send(self, messages: str = None):
        if self.ethernet is None:
            self.InitConnect()
        self.ethernet.sendto(messages, self.addr)

    def receive(self):
        if self.ethernet is None:
            self.InitConnect()
        data, addr = self.ethernet.recvfrom(1024)
        return data